package com.example.lc.mythreedemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lc.mythreedemo.custom.MyViewPage;

import java.util.ArrayList;
import java.util.List;

public class ImageCycleView extends FrameLayout {
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 图片轮播视图
     */
    private MyViewPage mViewPager;
    /**
     * 数据集合
     */
    private List<GridView> data;

    /**
     * 图片轮播指示器容器
     */
    private LinearLayout ll_indication_group;
    /**
     * 轮播的总数
     */
    private int mCount = 0;
    /**
     * GridView列数
     */
    private int grid_view_num_columns = 4;
    /**
     * viewpage每页显示条数
     */
    private int page_num = 4;
    /**
     * 未获得焦点指示器资源
     */
    private Bitmap unFocusIndicationStyle;
    /**
     * 获得焦点指示器资源
     */
    private Bitmap focusIndicationStyle;
    /**
     * 指示器间距相对于自身的百分比,默认间距为指示器高度的
     */
    private float indication_self_margin_percent = 1f;
    /**
     * 图片轮播是自动滚动状态  true 自动滚动，false 图片不能自动滚动只能手动左右滑动
     */
    public boolean isAutoCycle = true;
    /**
     * 自动轮播时间间隔默认5秒
     */
    private long mCycleDelayed = 5000;

    OnPageItemClickListener onpageitemclicklistener;
    OnMoreClickListener onmoreclicklistener;
    private TextView light_type;

    public ImageCycleView(Context context) {
        super(context);
        init(context);
    }

    public ImageCycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
//		init(context);
    }

    /**
     * 初始化基础信息
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        unFocusIndicationStyle = drawCircle(50, Color.BLACK);
        focusIndicationStyle = drawCircle(50, Color.GRAY);
        initView();
    }


    /**
     * viewpage每页显示条数
     */
    public void setPage_num(int page_num) {
        this.page_num = page_num;
    }


    /**
     * 初始化view控件
     *
     * @author 代凯男
     */
    private void initView() {
        View.inflate(mContext, R.layout.view_image_cycle, this);

        // 灯的类型,例如美式灯,新中式灯等等
        light_type = (TextView) findViewById(R.id.light_type);
        LinearLayout ll_more = (LinearLayout) findViewById(R.id.ll_more);
//        ll_more.setOnClickListener(onmoreclicklistener);

        ImageView iv_light_cover = (ImageView) findViewById(R.id.iv_light_cover);
        LinearLayout.LayoutParams iv_light_cover_params;
            // 其中后两位数字对应的图片宽高比,例美式灯中的阅简单,阅生活.这张图片
            iv_light_cover_params = new LinearLayout.LayoutParams(Graphic.getScreenWH(Graphic.TAG_WIDTH), (Graphic.getScreenWH(Graphic.TAG_WIDTH) * 50) / 131);
        iv_light_cover.setLayoutParams(iv_light_cover_params);

        FrameLayout fl_image_cycle = (FrameLayout) findViewById(R.id.fl_image_cycle);
        LinearLayout.LayoutParams fl_image_cycle_params;
            // 其中最后一位数字代表gridview中下面的文字内容所需要的高度dp
            fl_image_cycle_params = new LinearLayout.LayoutParams(Graphic.getScreenWH(Graphic.TAG_WIDTH), Graphic.getScreenWH(Graphic.TAG_WIDTH) / 4 + Graphic.dipToPixels(mContext, 50));
        fl_image_cycle.setLayoutParams(fl_image_cycle_params);

        mViewPager = new MyViewPage(mContext);
        mViewPager.setImagecycleview(this);
        mViewPager.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        fl_image_cycle.addView(mViewPager);
        mViewPager.addOnPageChangeListener(new ImageCyclePageChangeListener());

        ll_indication_group = (LinearLayout) findViewById(R.id.ll_indication_group);
    }


    public void initData(List<EnterpriseHomeEntity> original_data) {
        data = new ArrayList<GridView>();
        //总的页数向上取整 1.0的作用在于精确计算值
        mCount = (int) Math.ceil(original_data.size() * 1.0 / page_num);
        for (int i = 0; i < mCount; i++) {
            //每个页面都是inflate出一个新实例
            final GridView gridView = (GridView) View.inflate(mContext, R.layout.item_gridview, null);
            gridView.setNumColumns(grid_view_num_columns);
            // 以下两行代码解决在ScrollView中自动轮播时会已轮播区域为屏幕上方的问题.
            gridView.setFocusable(false);
            // gridView.setFocusableInTouchMode(false);


                gridView.setAdapter(new MyGridViewAdpter(mContext, original_data, i, page_num, grid_view_num_columns, 1, 1));

            //添加item点击监听
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int position, long arg3) {
                    Object obj = gridView.getItemAtPosition(position);
                    if (obj != null && obj instanceof EnterpriseHomeEntity) {
//                        Toast.makeText(mContext, ((EnterpriseHomeEntity) obj).getHref(), Toast.LENGTH_SHORT).show();
                        onpageitemclicklistener.onItemClick((EnterpriseHomeEntity) obj, position);
                    }
                }
            });
            //每一个GridView作为一个View对象添加到ViewPager集合中
            data.add(gridView);
        }


        initIndication();
        mViewPager.setAdapter(new ImageCycleAdapter());
        //最大值中间 的第一个
        mViewPager.setCurrentItem(Integer.MAX_VALUE / 2 - ((Integer.MAX_VALUE / 2) % mCount));

        light_type.setText("记得设置灯的类型");
    }

    /**
     * 设置是否自动无限轮播
     *
     * @param delayed 自动轮播时间间隔
     */
    public void setCycleDelayed(long delayed) {
        mCycleDelayed = delayed;
    }

    /**
     * 设置是否自动无限轮播
     *
     * @param state
     */
    public void setAutoCycle(Boolean state) {
        isAutoCycle = state;
    }

    /**
     * GridView列数
     *
     * @param grid_view_num_columns
     */
    public void setGridViewRumColumns(int grid_view_num_columns) {
        this.grid_view_num_columns = grid_view_num_columns;
    }

    /**
     * 轮播控件的监听事件
     */
    public interface OnPageItemClickListener {
        void onItemClick(EnterpriseHomeEntity enterprisehomeentity, int position);
    }

    /**
     * 更多控件的监听事件
     */
    public interface OnMoreClickListener {
        void onMoreClick(int position);
    }

    public void setOnpageitemclicklistener(OnPageItemClickListener onpageitemclicklistener) {
        this.onpageitemclicklistener = onpageitemclicklistener;
    }
    public void setOnMoreClickListener(OnMoreClickListener onmoreclicklistener) {
        this.onmoreclicklistener = onmoreclicklistener;
    }
    /**
     * 初始化指标器
     */
    private void initIndication() {
        // 清楚所有指示器点
        ll_indication_group.removeAllViews();
        for (int i = 0; i < mCount; i++) {
            ImageView imageView = new ImageView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ll_indication_group.getLayoutParams().height, LinearLayout.LayoutParams.MATCH_PARENT);
            params.leftMargin = (int) (ll_indication_group.getLayoutParams().height * indication_self_margin_percent);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(params);
            if (i == 0) {
                imageView.setImageBitmap(focusIndicationStyle);
            } else {
                imageView.setImageBitmap(unFocusIndicationStyle);
            }
            ll_indication_group.addView(imageView);
        }
    }

    private Bitmap drawCircle(int radius, int color) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);// 设置颜色
        Bitmap bitmap = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawCircle(radius / 2, radius / 2, radius / 2, paint);
        return bitmap;
    }


    /**
     * 轮播图片监听
     *
     * @author 代凯男
     */
    private final class ImageCyclePageChangeListener implements OnPageChangeListener {

        //上次指示器指示的位置,开始为默认位置0
        private int preIndex = 0;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            position = position % mCount;
            //恢复默认没有获得焦点指示器样式
            ((ImageView) (ll_indication_group.getChildAt(preIndex))).setImageBitmap(unFocusIndicationStyle);
            // 设置当前显示图片的指示器样式
            ((ImageView) (ll_indication_group.getChildAt(position))).setImageBitmap(focusIndicationStyle);
            preIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    /**
     * 图片轮播适配器
     */
    private class ImageCycleAdapter extends PagerAdapter {

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            GridView gridView = data.get(position % mCount);
            // TODO 这里不知道为什么要这么写,涉及的知识点会比较深入,有能力了再回过头来看
            container.removeView(gridView);
            container.addView(gridView);
            return gridView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            container.removeView((GridView)object);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }
    }


    /**
     * 开始图片轮播
     */
    public void startImageCycle() {
        handler.sendEmptyMessageDelayed(0, mCycleDelayed);
    }

    /**
     * 暂停图片轮播
     */
    public void stopImageCycle() {
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 实现自动轮播
     */
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                handler.sendEmptyMessageDelayed(0, mCycleDelayed);
            }
            return false;
        }
    });

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 停止图片滚动
        stopImageCycle();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isAutoCycle) {
            startImageCycle();
        }
    }

}